package com.example.zkviewer.controller;

import com.example.zkviewer.model.ZkNode;
import com.example.zkviewer.service.ZookeeperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/")
public class ZookeeperController {

    @Autowired
    private ZookeeperService zookeeperService;
    
    @Value("${zookeeper.root.path}")
    private String rootPath;

    // 主页面，显示根节点的子节点
    @GetMapping
    public String index(Model model) {
        return viewNode(rootPath, model);
    }

    // 查看指定节点
    @GetMapping("/view")
    public String viewNode(@RequestParam(value = "path", required = false) String path,
                          Model model) {
        // 如果没有提供路径参数，使用配置的根路径
        if (path == null || path.isEmpty()) {
            path = rootPath;
        }
        try {
            ZkNode node = zookeeperService.getNodeData(path);
            if (node != null) {
                model.addAttribute("node", node);
                if (!node.isLeaf()) {
                    List<ZkNode> children = zookeeperService.getChildren(path);
                    model.addAttribute("children", children);
                }
                model.addAttribute("successMessage", "成功获取节点信息");
            } else {
                model.addAttribute("errorMessage", "节点不存在: " + path);
            }
        } catch (Exception e) {
            model.addAttribute("errorMessage", "获取节点信息失败: " + e.getMessage());
        }
        model.addAttribute("currentPath", path);
        return "index";
    }

    // 创建节点表单
    @GetMapping("/create")
    public String createNodeForm(@RequestParam(value = "parentPath", required = false) String parentPath,
                                Model model) {
        // 如果没有提供父路径参数，使用配置的根路径
        if (parentPath == null || parentPath.isEmpty()) {
            parentPath = rootPath;
        }
        model.addAttribute("parentPath", parentPath);
        model.addAttribute("node", new ZkNode());
        return "create-node";
    }

    // 创建节点提交
    @PostMapping("/create")
    public String createNode(@RequestParam String parentPath,
                           @RequestParam String nodeName,
                           @RequestParam(required = false) String nodeData,
                           @RequestParam(required = false, defaultValue = "false") boolean ephemeral,
                           RedirectAttributes redirectAttributes) {
        try {
            // 构建完整路径
            String fullPath = parentPath.equals("/") ? "/" + nodeName : parentPath + "/" + nodeName;
            
            boolean success = zookeeperService.createNode(fullPath, nodeData, ephemeral);
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "节点创建成功: " + fullPath);
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "节点创建失败: 节点已存在或其他错误");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "创建节点失败: " + e.getMessage());
        }
        return "redirect:/view?path=" + parentPath;
    }

    // 编辑节点表单
    @GetMapping("/edit")
    public String editNodeForm(@RequestParam String path,
                              Model model) {
        try {
            ZkNode node = zookeeperService.getNodeData(path);
            if (node != null) {
                model.addAttribute("node", node);
                // 获取父路径
                String parentPath = path.equals(rootPath) ? rootPath : path.substring(0, path.lastIndexOf('/'));
                model.addAttribute("parentPath", parentPath);
            } else {
                model.addAttribute("errorMessage", "节点不存在: " + path);
                return "redirect:/view?path=" + rootPath;
            }
        } catch (Exception e) {
            model.addAttribute("errorMessage", "获取节点信息失败: " + e.getMessage());
            return "redirect:/view?path=/";
        }
        return "edit-node";
    }

    // 编辑节点提交
    @PostMapping("/edit")
    public String editNode(@RequestParam String path,
                         @RequestParam(required = false) String nodeData,
                         RedirectAttributes redirectAttributes) {
        try {
            boolean success = zookeeperService.updateNode(path, nodeData);
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "节点更新成功: " + path);
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "节点更新失败: 节点不存在或其他错误");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "更新节点失败: " + e.getMessage());
        }
        // 返回父节点页面
        String parentPath = path.equals(rootPath) ? rootPath : path.substring(0, path.lastIndexOf('/'));
        return "redirect:/view?path=" + parentPath;
    }

    // 删除节点
    @GetMapping("/delete")
    public String deleteNode(@RequestParam String path,
                           RedirectAttributes redirectAttributes) {
        try {
            // 获取父路径
            String parentPath = path.equals(rootPath) ? rootPath : path.substring(0, path.lastIndexOf('/'));
            
            boolean success = zookeeperService.deleteNode(path);
            if (success) {
                redirectAttributes.addFlashAttribute("successMessage", "节点删除成功: " + path);
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "节点删除失败: 节点不存在或其他错误");
            }
            return "redirect:/view?path=" + parentPath;
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "删除节点失败: " + e.getMessage());
            return "redirect:/view?path=" + rootPath;
        }
    }

    // 批量删除节点
    @PostMapping("/batch-delete")
    public String batchDeleteNodes(@RequestParam String selectedPaths,
                                 @RequestParam String returnPath,
                                 RedirectAttributes redirectAttributes) {
        try {
            // 解析选中的路径列表
            List<String> paths = Arrays.asList(selectedPaths.split(","));
            
            boolean allSuccess = zookeeperService.deleteNodes(paths);
            
            if (allSuccess) {
                redirectAttributes.addFlashAttribute("successMessage", "成功删除 " + paths.size() + " 个节点");
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "部分节点删除失败，请检查日志");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "批量删除节点失败: " + e.getMessage());
        }
        
        return "redirect:/view?path=" + returnPath;
    }
    
    // 健康检查API
    @GetMapping("/health")
    @ResponseBody
    public Map<String, String> health() {
        Map<String, String> response = new HashMap<>();
        try {
            boolean isConnected = zookeeperService.exists(rootPath);
            if (isConnected) {
                response.put("status", "UP");
                response.put("message", "Zookeeper连接正常");
            } else {
                response.put("status", "DOWN");
                response.put("message", "Zookeeper连接异常");
            }
        } catch (Exception e) {
            response.put("status", "DOWN");
            response.put("message", "Zookeeper连接异常: " + e.getMessage());
        }
        return response;
    }
}